package com.winning.dps.ds.common;


import com.winning.dps.ds.service.common.CommonApiService;
import common.entity.*;
import common.util.Common;
import common.util.ResponseEntity;
import common.util.TreeUtil;
import common.util.file.FileUtils;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;

/**
 * @Author: nxs@winning.com.cn
 *
 * @Description:  公共接口类封装
 *
 * @Date: 2018-07-05 17:17:45
 *
 *
 **/
@RestController
@RequestMapping("/commonapi")
@Api(description="基础平台公共接口")
@Slf4j
public class CommonApi extends BaseController {

    private static String FILENAME="";

    @Autowired
    private CommonApiService commonApiService;

    @Value("${spring.application.yydm:DQMT}")
    public String yydm;

    @Value("${mbParPath_Ypml}")
    public String mbParPath_Ypml;

    //图片或文件上传路径
    @Value("${upload-path}")
    public String uploadPath;

    public String platResource = "plat-resource";

    private final ResourceLoader resourceLoader;


    /**
     * 查询机构树形列表  ztree类型
     *
     * @param jgdm
     * @return ResponseEntity
     */
    @RequestMapping(value = "/jgtree/{jgdm}", method = RequestMethod.GET)
    public ResponseEntity findJgTreeParams(@PathVariable String jgdm) {
        Map<String,Object> queryParams = new HashMap<String,Object>();
        queryParams.put("jgbm",jgdm);
        List<TreeEntity> jgTreeList = commonApiService.findJgTree(queryParams);
        return ResponseEntity.ok().put("jgTreeList", jgTreeList);
    }


    /**
     * 根据机构编码查询机构详情
     *
     * @param jgdm
     * @return ResponseEntity
     */
    @RequestMapping(value = "/jginfo/{jgdm}", method = RequestMethod.GET)
    public ResponseEntity jgInfo(@PathVariable String jgdm) {
        if (!Common.validateParams(jgdm)) {
            return ResponseEntity.error(201, "机构代码不能为空");
        }
        SysZcjgEntity syszcjgeneity = commonApiService.getJgInfo(jgdm);
        return ResponseEntity.ok().put("syszcjgeneity", syszcjgeneity);
    }


    /**
     * 获取当前登录机构的树  ztree类型
     *
     * @return ResponseEntity
     */
    @RequestMapping(value = "/findjgtree", method = RequestMethod.GET)
    public ResponseEntity findJgTree(@RequestParam Map<String,Object> queryParams) {

        String jgbm = getJgbm();
        queryParams.put("jgbm",jgbm);
        List<TreeEntity> jgTreeList = commonApiService.findJgTree(queryParams);
        SysQjcsEntity qjcsEntity = commonApiService.queryQjcs("dqms_xmxc");
        qjcsEntity = Optional.ofNullable(qjcsEntity).orElse(new SysQjcsEntity());
        if(!"FX".equals(qjcsEntity.getCsz())){
            jgTreeList = new TreeUtil().builTree(jgTreeList, jgbm);
        }

        return ResponseEntity.ok().put("jgTreeList", jgTreeList);
    }

    /**
     * 获取当前登录机构的树  ztree类型
     *
     * @return ResponseEntity
     */
    @RequestMapping(value = "/findzkjgtree", method = RequestMethod.GET)
    public ResponseEntity findzkjgtree(@RequestParam Map<String,Object> queryParams) {
        String jgbm = (String)queryParams.get("jgbm");
        if(StringUtils.isEmpty(jgbm)) {
            jgbm = getJgbm();
            queryParams.put("jgbm",jgbm);
        }
        List<TreeEntity> jgTreeList = commonApiService.findZkJgTree(queryParams);
        jgTreeList = new TreeUtil().builTree(jgTreeList, jgbm);

        return ResponseEntity.ok().put("jgTreeList", jgTreeList);
    }
  /**
   * 获取当前登录机构的树  ztree类型
   *
   * @return ResponseEntity
   */
  @RequestMapping(value = "/findZkzcjgTree", method = RequestMethod.GET)
  public ResponseEntity findSysEsbJgTree(@RequestParam Map<String,Object> queryParams) {
      String jgbm = (String)queryParams.get("jgbm");
      if(StringUtils.isEmpty(jgbm)) {
          jgbm = getJgbm();
          queryParams.put("jgbm",jgbm);
      }
      List<TreeEntity> jgTreeList = commonApiService.findZcjgTree(queryParams);
      jgTreeList = new TreeUtil().builTree(jgTreeList, jgbm);


    return ResponseEntity.ok().put("jgTreeList", jgTreeList);
  }

    @RequestMapping(value = "/findjgtreeByPid", method = RequestMethod.GET)
    public ResponseEntity findjgtreeByPid(HttpServletRequest request, @RequestParam Map<String,Object> queryParams) {
        List<TreeEntity> jgTreeList = commonApiService.findjgtreeByPid(queryParams);
        return ResponseEntity.ok().put("jgTreeList", jgTreeList);
    }

    /**
     * 获取当前登录机构编码
     *
     * @return ResponseEntity
     */
    @RequestMapping(value = "/jgbm", method = RequestMethod.GET)
    public ResponseEntity Jgbm() {
        String jgbm = getJgbm();
        CommonJgUserEntity user = getUser();
        String jgmc = user.getJgmc();
        return ResponseEntity.ok().put("jgbm", jgbm).put("jgmc",jgmc).put("jglb", user.getJglb());
    }

    /**
     * 根据值域代码查询该值域信息
     *
     * @param zydm
     * @return ResponseEntity
     */
    @RequestMapping(value = "/zyinfo", method = RequestMethod.GET)
    public ResponseEntity sysSjyzymlInfo(@RequestParam("zydm") String zydm) {

        if (!Common.validateParams(zydm)) {
            return ResponseEntity.error(201, "值域代码不能为空");
        }
        List<SysSjyzymlEntity> sse = new ArrayList<>();
//        if (EhcacheUtil.zyCache.get(zydm) != null && EhcacheUtil.zyCache.get(zydm).size() > 0) {
//            sse = EhcacheUtil.zyCache.get(zydm);
//        } else {
            sse = commonApiService.sysSjyzymlInfo(zydm);
//            EhcacheUtil.zyCache.put(zydm, sse);
//        }
        return ResponseEntity.ok().put("sjyzymlEntity", sse);
    }


    /**
     * 查询应用
     *
     * @return ResponseEntity
     */
    @RequestMapping(value = "/queryApplication", method = RequestMethod.GET)
    public ResponseEntity findRoleList() {
        List<SysYyzcEntity> list = commonApiService.queryApplication();
        return ResponseEntity.ok().put("list", list);
    }




    /**
     * 获取当前操作人员的角色权限 (包含未授权按钮)
     * 前端按钮权限过滤时使用
     * @return ResponseEntity 无权限按钮
     *
     */
    @RequestMapping(value = "/getCzryqx/{mcode}", method = RequestMethod.GET)
    public ResponseEntity getCzryqx(@PathVariable String mcode) {

        if (!Common.validateParams(mcode)) {
            return ResponseEntity.error(201, "无法获取菜单编号");
        }
        String zclsh = getUser().getZclsh();
        String jgbm = getUser().getJgbm();
        //查询该操作人员权限包含菜单和功能按钮
        List<SysCzjsQxEntity> qxlist =  commonApiService.getCzryqx(jgbm, zclsh,yydm);
        //查询该菜单下所有功能按钮
        //重组数据
        List<String> tempQxList = new ArrayList<>();
        for(SysCzjsQxEntity scqe : qxlist)
        {
            tempQxList.add(scqe.getCddm());
        }

        List noQxlist = new ArrayList<>();


        return ResponseEntity.ok().put("noQxlist", noQxlist);
    }


    /**
     * 根据机构编码 查询所有下级
     *
     * @param jgdm
     * @return ResponseEntity
     */
    @RequestMapping(value = "/jgSubinfo/{jgdm}", method = RequestMethod.GET)
    public ResponseEntity jgSubInfo(@PathVariable String jgdm) {
        if (!Common.validateParams(jgdm)) {
            return ResponseEntity.error(201, "机构代码不能为空");
        }
        List<SysZcjgEntity> list = commonApiService.getSubJg(jgdm);
        return ResponseEntity.ok().put("list", list);
    }

    /**
     * 查询当前机构和子机构
     * @param jgbm
     * @return
     */
    public List<SysZcjgEntity> querySubJg(String jgbm) {

        List<SysZcjgEntity> list = new ArrayList<SysZcjgEntity>();
        SysZcjgEntity syszcjgeneity = commonApiService.getJgInfo(jgbm);

        ResponseEntity subjgbm = jgSubInfo(jgbm);
        list = ( List<SysZcjgEntity>)subjgbm.get("list");

        list.add(syszcjgeneity);
        return list;
    }

    /**
     * @Author: nxs@winning.com.cn
     *
     * @Description:  图片或文件上传
     *
     * @Date: 2018-08-31 15:17:56
     *
     *
     **/
    @RequestMapping(value = "/fileUpload", method = RequestMethod.POST)
    public ResponseEntity upload(@RequestParam("fileName") MultipartFile file, Map<String, Object> map){

        String newFileName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('\\') + 1);
        newFileName = validateFile(newFileName);//检验名称
        if(StringUtils.isEmpty(newFileName)){
            return ResponseEntity.error().put("msg", "文件路径或格式有误");
        }
        if (FileUtils.upload(file, platResource, newFileName)){
            FILENAME=newFileName;
            return ResponseEntity.ok().put("fileName", newFileName);
        }else {
            return ResponseEntity.error().put("msg", "上传失败");
        }
    }

    @Autowired
    public CommonApi(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    /**
     * 显示单张图片
     * @return
     */
   @RequestMapping(value = "/showFile", method = RequestMethod.GET)
    public org.springframework.http.ResponseEntity showPhotos(String fileName){
        try {
            /*if(!StringUtils.isEmpty(FILENAME)){
                fileName=FILENAME;
            }*/
            fileName = validateFile(fileName);//检验名称
            if(StringUtils.isEmpty(fileName)){
                throw  new Exception();
            }

            FileUtils fu = new FileUtils();
            String realUploadPath = fu.getUploadPath(platResource);
            //String realUploadPath = this.getClass().getResource(uploadPath).getPath();
            // Resource resource = resourceLoader.getResource("file:" + realUploadPath +"/"+ fileName);
            // System.out.println("file：----" +realUploadPath);

            File mbFile = ResourceUtils.getFile("file:" + realUploadPath );
            String path = mbFile.getPath();
            Resource resource = resourceLoader.getResource("file:" + path +"/"+ fileName);
            System.out.println("mbFile：----" +mbFile);
            System.out.println("file：----" +path);
            return org.springframework.http.ResponseEntity.ok(resource);
        } catch (Exception e) {
            return org.springframework.http.ResponseEntity.notFound().build();
        }
    }

    /**
     * 检验文件路径
     * @return
     */

    public String validateFile(String fileName){
        String name=null;
        try {
            //所有合法的文件后缀
            String [] str1=fileName.split("/");
            fileName=str1[ str1.length-1];
            //返回在此字符串中最右边出现的指定子字符串的索引
            String sname = fileName.substring(fileName.lastIndexOf("."));
            //转换为小写
            sname=sname.toLowerCase();

/*            if(sname.contains("jpg") || sname.contains("png")  || sname.contains("bmp")){

            }*/
            name=fileName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return name;
    }


    /**
     * 全局参数接口
     *
     * @return ResponseEntity
     */
    @RequestMapping(value = "/queryQjcs/{csbm}", method = RequestMethod.GET)
    public ResponseEntity queryQjcs(@PathVariable String csbm) {
        if (!Common.validateParams(csbm)) {
            return ResponseEntity.error(201, "参数编码不能为空");
        }
        SysQjcsEntity qjcsEntity = commonApiService.queryQjcs(csbm);
        return ResponseEntity.ok().put("qjcsEntity", qjcsEntity);
    }

    /**
     * 获取要下载的文件路径
     * @param filename
     * @return
     */
    public String getFileName(String filename){
        FileUtils fu = new FileUtils();
        String realUploadPath = fu.getUploadPath(uploadPath);
        String mbParPath=realUploadPath+ "/"+filename;
        File tempFile = null;
        tempFile = new File(mbParPath);
        if (tempFile.exists()) {
            return mbParPath;
        }else {
            return "";
        }

    }

    /**
     * 文档管理-下载文件
     * @param
     * @param response
     * @param
     */
    @RequestMapping(value = "/exportFile", method = RequestMethod.GET)
    public  void exportFile(String filename,HttpServletRequest request,HttpServletResponse response) {
        FileInputStream fs = null;
        OutputStream os =null;
        try {
            // String realUploadPath = this.getClass().getResource(uploadPath).getPath();
            FileUtils fu = new FileUtils();
            String realUploadPath = fu.getUploadPath(platResource);
            String mbParPath=realUploadPath+ "/"+filename;
            File tempFile = ResourceUtils.getFile(mbParPath);
            System.out.print("tempFile====="+tempFile);
            fs = new FileInputStream(tempFile);
//            response.setContentType("APPLICATION/DOWNLOAD");
            response.setContentType("application/octet-stream");
            response.setHeader("content-disposition","attachment;filename="+ URLEncoder.encode(tempFile.getName(),"UTF-8").replaceAll("\\+", "%20"));
//            response.setContentLength(fs.available());
            os = response.getOutputStream();
            int iBytesRead = 0;
            byte[] buffer = new byte[8192];
            while((iBytesRead = fs.read(buffer,0,8192))!=-1){
                os.write(buffer,0,iBytesRead);
            }
            response.flushBuffer();
            //统计下载次数
//            queryXzLog("2",filename);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            try {
                fs.close();
                os.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    /**
     * 下载文件
     * @param
     * @param response
     * @param
     */
    @RequestMapping(value = "/downFile", method = RequestMethod.GET)
    public void downFile(String filePath,String fileName,HttpServletResponse response) throws Exception {
        filePath = StringUtils.trim(filePath);
        File file = new File(filePath);
        if (!file.exists()) {
            System.out.println("文件目录：" + file + "不存在.");
            log.error("文件路径：" + file.getAbsolutePath());
            log.error("文件目录：" + file.getPath() + "不存在.");
        } else {
            try {
                // 以流的形式下载文件。
                InputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));
                byte[] buffer = new byte[fis.available()];
                fis.read(buffer);
                fis.close();
                // 清空response
                response.reset();

                OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
                response.setContentType("application/octet-stream");

                // 如果输出的是中文名的文件，在此处就要用URLEncoder.encode方法进行处理
                response.setHeader("Content-Disposition",
                        "attachment;filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1"));
                toClient.write(buffer);
                toClient.flush();
                toClient.close();
            } catch (Exception ex) {
                log.error("下载异常：", ex);
            } finally {
                try {
                    File f = new File(file.getPath());
                    f.delete();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
    /**
     * @Author zhanglei
     * @Description 将文件以流的形式保存到数据库
     * @Date 10:50 2019/4/16
     * @Param [file]
     * @return com.winning.plat.common.util.ResponseEntity
     **/
    @RequestMapping(value = "/saveFileToDb", method = RequestMethod.POST)
    public ResponseEntity saveFileToDb(HttpServletRequest request,HttpServletResponse response,
                                       @RequestParam("fileName") MultipartFile file) {
        String newFileName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('\\') + 1);
        try {
            request.setCharacterEncoding("utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        byte[] bytes = new byte[0];
        if(!file.isEmpty()){
            try {
                bytes = file.getBytes();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        String tableName = request.getParameter("tableName");
        String colName = request.getParameter("colName");
        String id = request.getParameter("id");
        String idValue = request.getParameter("idValue");
        commonApiService.saveFileToDb(tableName,colName,bytes,id,idValue);
        return ResponseEntity.ok().put("fileName", newFileName);
    }


    @RequestMapping(value = "/queryCsbm/{csbm}", method = RequestMethod.GET)
    public ResponseEntity queryCsbm(@PathVariable String csbm){
        SysQjcsEntity sysQjcsEntity  = commonApiService.queryCsbm(csbm);
        return ResponseEntity.ok().put("csz",sysQjcsEntity==null?"":sysQjcsEntity.getCsz());
    }

    /**
     * 下载模板,浏览器下载
     * @param
     * @param tempFileName
     * @param
     */
    @RequestMapping(value = "/exportExcel_Model", method = RequestMethod.GET)
    public  void exportExcel_Model(HttpServletRequest request,HttpServletResponse response,String tempFileName) {
        FileInputStream fs = null;
        OutputStream os =null;
        try {
            // String realUploadPath = this.getClass().getResource(uploadPath).getPath();
            String mbParPath=mbParPath_Ypml+ tempFileName;
            File tempFile = ResourceUtils.getFile(mbParPath);
            System.out.println("tempFile====="+tempFile);
            fs = new FileInputStream(tempFile);
            response.setContentType("APPLICATION/DOWNLOAD");
            response.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(tempFile.getName(),"UTF-8"));
            response.setContentLength(fs.available());
            os = response.getOutputStream();
            int iBytesRead = 0;
            byte[] buffer = new byte[8192];
            while((iBytesRead = fs.read(buffer,0,8192))!=-1){
                os.write(buffer,0,iBytesRead);
            }
            response.flushBuffer();

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            try {
                fs.close();
                os.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取当前登录所在机构和下级所有
     * @return
     */
    @GetMapping("listTree")
    public ResponseEntity listTree(){
        String jgbm = getJgbm();
        Map<String,String> map = new HashMap<>(1);
        map.put("jgbm",jgbm);
        List<SysEsbZcjgEntity> jgList = commonApiService.getAllJg(map);
        SysEsbZcjgEntityTree tree = getSysEsbZcjgEntityTree(jgList,jgbm);
        assert tree != null;
        tree.setChildren(getTree(jgList,jgbm));
        List<SysEsbZcjgEntityTree> treeList = new ArrayList<>();
        treeList.add(tree);
        return ResponseEntity.ok().put("rows",treeList);
    }


    private SysEsbZcjgEntityTree getSysEsbZcjgEntityTree(List<SysEsbZcjgEntity> jgList,String jgbm){
        for(SysEsbZcjgEntity zcjg : jgList){
            if(jgbm.equalsIgnoreCase(zcjg.getJgbm())){
                SysEsbZcjgEntityTree entityTree = SysEsbZcjgEntityTree.clone(zcjg);
                entityTree.setJgmc(zcjg.getJgmc());
                entityTree.setJgbm(zcjg.getJgbm());
                return entityTree;
            }
        }
        return null;
    }

    /**
     * 条件获取所有机构
     * @param map
     * @return
     */
    @PostMapping("getAlljg")
    public ResponseEntity getAlljg(Map map){
        List<SysEsbZcjgEntity> jgList = commonApiService.getAllJg(map);
        return ResponseEntity.ok().put("rows",jgList);
    }


    private List<SysEsbZcjgEntityTree> getTree(List<SysEsbZcjgEntity> jgList,String sjjgdm){
        List<SysEsbZcjgEntityTree> children = null;
        for (int i = 0; i < jgList.size(); i++) {
            SysEsbZcjgEntity entity = jgList.get(i);
            if (sjjgdm.equals(entity.getSjjgbm())) {
                SysEsbZcjgEntityTree entityTree = SysEsbZcjgEntityTree.clone(entity);
                entityTree.setJgmc(entity.getJgmc());
                entityTree.setJgbm(entity.getJgbm());
                List<SysEsbZcjgEntityTree> node = getTree(jgList,entity.getJgbm());
                entityTree.setChildren(node);
                if (children == null) {
                    children = new ArrayList<>();
                }
                children.add(entityTree);
            }
        }
        return children;
    }

    @RequestMapping(value = "/judgeWjjYy", method = RequestMethod.GET)
    public ResponseEntity judgeWjj(){
        String  jgbm = getJgbm();
        return ResponseEntity.ok().put("data", commonApiService.judgeWjjYy(jgbm));
    }


    /**
     * 获取当前登录机构的树  ztree类型
     */
    @RequestMapping(value = "/findSjbzTree", method = RequestMethod.GET)
    public ResponseEntity findSjbzTree() {
        List<TreeEntity> jgTreeList = commonApiService.findSjbzTree();
        jgTreeList = new TreeUtil().builTree(jgTreeList, "ROOT");

        return ResponseEntity.ok().put("jgTreeList", jgTreeList);
    }

    /**
     * @description 获取当前登录用户机构及子机构
     * @author DANGBO
     * @date 2022/6/29 15:03:19
     * @params []
     * @return ResponseEntity
     */
    @RequestMapping(value = "/findYljgdmByUser", method = RequestMethod.GET)
    public ResponseEntity findYljgdmByUser() {
        String jgbm = getJgbm();
        String yljgdms = commonApiService.findYljgdmByUser(jgbm);
        return ResponseEntity.ok().put("yljgdms", yljgdms);
    }
}
